<template>
  <base-layout
    :dialogVisible="dialogVisible"
    :dialogTitle="dialogTitle"
    @dialog-close="dialogClose"
    :visibleContent2="true"
    :visibleContent3="true"
    :visibleContent4="true"
    :visibleContent5="true"
  >
    <template #searchPanel>
      <el-form
        :inline="true"
        ref="fromdata"
        :show-message="false"
        :hide-required-asterisk="true"
        :model="fromdata"
        :rules="rules"
        label-width="90px"
        label-position="right"
      >
        <CustomerSearch
          :addCustomer="true"
          @clientForm="customerInfo"
        />
      </el-form>
    </template>
    <template #contentPanel>
      <el-form
        :inline="true"
        ref="fromdata"
        :show-message="false"
        :hide-required-asterisk="true"
        :model="fromdata"
        :rules="rules"
        label-width="90px"
        label-position="right"
      >
        <el-row>
          <el-col :span="12">客户信息</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item
              label="客户类型:"
              prop="clientType"
            >
              <el-radio-group v-model="fromdata.client.clientType">
                <el-radio-button
                  v-for="item in dict['客户类型']"
                  :key="item.index"
                  :label="item.text"
                  :value="item.value"
                >{{ item.text }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="客户名称:"
              prop="clientName"
            >
              <el-input
                clearable
                v-model="fromdata.client.clientName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="手机号:"
              prop="phone"
            >
              <el-input
                clearable
                v-model.number="fromdata.client.phone"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item
              label="驾驶证号:"
              prop="jszNum"
            >
              <el-input
                clearable
                v-model="fromdata.client.jszNum"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="会员等级:"
              prop="levelId"
            >
            <el-input
                clearable
                disabled
                v-model="fromdata.client.memberLevelDictValue"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item
              label="地址:"
              prop="address"
            >
              <el-input
                clearable
                v-model.number="fromdata.client.address"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template #contentPanel2>
      <el-form
        :inline="true"
        ref="fromdata"
        :show-message="false"
        :hide-required-asterisk="true"
        :model="fromdata"
        :rules="rules"
        label-width="90px"
        label-position="right"
      >
        <el-row>
          <el-col :span="12">销售单信息</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item
              label="销售单编号:"
              prop="workOrderCode"
            >
              <el-input
                clearable
                disabled
                v-model="fromdata.workOrderCode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="单据日期:"
              prop="receiptsTime"
            >
              <el-date-picker
                disabled
                v-model="fromdata.receiptsTime"
                type="date"
                style="width: 195px"
                placeholder="请选择"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="销售人员:"
              prop="receiptsTime"
            >
              <el-input
                clearable
                v-model="fromdata.receptionName"
                @focus="employeeFocus()"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="销售备注:"
              prop="remark"
            >
              <textarea
                clearable
                v-model="fromdata.remark"
              ></textarea>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template #contentPanel3>
      <div v-if="fromdata.workOrderCode">
        <PartsList
          ref="PartsList"
          @setTotalAmount="setTotalAmount"
          :list="fromdata.orderSellPartsList"
        />
      </div>
    </template>
    <template #contentPanel4>
      <div v-if="fromdata.workOrderCode">
        <BoutiqueList
          ref="BoutiqueList"
          @setTotalAmount="setTotalAmount"
          :list="fromdata.jpList"
        />
      </div>
    </template>
    <template #contentPanel5>
      <div
        class="text_right"
        v-if="fromdata.workOrderCode"
      >
        <p>
          配件总金额： <span class="color_red">￥{{ fromdata.amount }}</span>
        </p>
        <p>
          配件优惠金额：
          <span class="color_red">￥{{ fromdata.discountAmount }}</span>
        </p>
        <p>
          已交定总金额： <span class="color_red">￥{{ 0 }}</span>
        </p>
        <p>
          应付金额：
          <span class="color_red">￥{{ fromdata.shouldAmount }}</span>
        </p>
        <p>
          <el-button
            type="primary"
            @click="submitOrder"
          >{{
            fromdata.id ? "保存" : "开单"
          }}</el-button>
        </p>
      </div>
    </template>

    <template #dialog>
      <EmployeeTable @roleIdListSelectCheck="employeListSelectCheck" />
    </template>
  </base-layout>
</template>
<script>
import baseMixin from "@/mixins/base";
import { CustomerSearch } from "@/components/index"; //导入组件库
import { parseTimeToYMDHMS, getDict, getStoreId, getUser } from "@/utils";
import {
  addSell,
  getSellFindById,
  editSell,
  sellGetWorkOrderCode,
} from "@/api/after-sale/workOrderManage/sell";
import PartsList from "@/views/after-sale/workOrderManage/sell/create/partsList"; //拆分-配件列表
import BoutiqueList from "@/views/after-sale/workOrderManage/sell/create/boutiqueList"; //拆分-精品列表
import EmployeeTable from "@/views/after-sale/systemManage/store/components/EmployeeTable";
import moment from 'moment';
export default {
  components: { CustomerSearch, PartsList, BoutiqueList, EmployeeTable },
  mixins: [baseMixin({})],
  data () {
    return {
      fromdata: {
        client: {
          address: "",
          birthday: "",
          cars: [],
          clientLike: "",
          clientName: "",
          clientSource: "",
          clientType: "",
          companyName: "",
          companyTitle: "",
          createUser: "",
          genderCst: "",
          jszExpireTime: "",
          jszNum: "",
          memberLevelDictId: "",
          phone: "",
          remark: "",
          storeId: "",
        },
        clientId: null,
        imprest: "",
        memberGrade: "",
        orderSellPartsList: [], //配件列表
        jpList: [], //精品列表
        pickCarId: "",
        storeId: getStoreId(),
        workOrderCode: "",
        receiptsTime: "",
        remark: "",
        amount: 0,
        shouldAmount: 0,
        discountAmount: 0,
        receptionName: null,
      },
      rules: {},
      dict: {},
    };
  },
  async created () {
    this.fromdata.receiptsTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
    this.dict = getDict(["客户类型"]);
    const id = this.$route.query && this.$route.query.id;
    let pickCarId = this.$route.query.pickCarId;
    if (id) {
      const { data } = await getSellFindById(id);
      if (data) {
        this.fromdata = {
          ...this.fromdata,
          ...data,
        };
      }
    }
    // 接车单跳过来
    else if (pickCarId) {
      this.fromdata.pickCarId = pickCarId;
      let queryData = {};
      if (!id) {
        queryData = JSON.parse(JSON.stringify(this.$route.query.data));
      }
      const { data } = await sellGetWorkOrderCode();
      this.fromdata = { ...this.fromdata, ...queryData, workOrderCode: data };
      if(queryData.carProjects) {
        this.fromdata.projectList = queryData.carProjects;
      }
      if (queryData.carParts) {
        this.fromdata.orderSellPartsList = queryData.carParts;
      }
    } else {
      const { userInfo } = getUser();
      this.fromdata.receptionName = userInfo.userName;
      this.fromdata.receptionId = userInfo.id;
      const { data } = await sellGetWorkOrderCode();
      this.fromdata.workOrderCode = data;
      //如果不是详情，则判断是否是转工单
      let obj = JSON.parse(sessionStorage.getItem("pendingWorkOrder"));
      if (Object.keys(obj).length > 0) {
        let { type, carryInformation } = obj;
        carryInformation.carParts.map(item => {
          item.partsPrice = item.storagePrice;
        })
        this.fromdata = {
          ...this.fromdata,
          orderSellPartsList: carryInformation.carParts,
          clientId: carryInformation.client.id,
          client: carryInformation.client,
        };
        this.fromdata.client.cars = [carryInformation.car];
      }
    }
  },
  destroyed () {
    sessionStorage.removeItem("pendingWorkOrder");
  },
  watch: {},
  methods: {
    //设置总金额、优惠劵查询
    setTotalAmount () {
      const { PartsList, BoutiqueList } = this.$refs;
      this.fromdata.amount = (Number(PartsList.totalAmount) + Number(BoutiqueList.totalAmount)).toFixed(2);
      this.fromdata.shouldAmount =
        (Number(PartsList.totalDiscountAmount) + Number(BoutiqueList.totalDiscountAmount)).toFixed(2);
      this.fromdata.discountAmount = (Number(this.fromdata.amount) - Number(this.fromdata.shouldAmount)).toFixed(2);
    },
    customerInfo (values) {
      this.fromdata.clientId = values.id;
      values.sendRepairName = values.clientName;
      values.sendRepairPhone = values.phone;
      this.fromdata.client = { ...this.fromdata.client, ...values };
      let {
        discountInterval: { partsDiscount, projectDiscount },
      } = values; //获取折扣对象-包含用户权限折扣和会员卡折扣区间值
      //设置配件列表的折扣上下限
      this.$refs.PartsList.tableColumnAttributes.forEach((item) => {
        if (item.value == "discount") {
          item.maxFiled = partsDiscount.max;
          item.minFiled = partsDiscount.min;
        }
      });
    },
    employeeFocus () {
      this.dialogVisible = true;
      this.dialogTitle = "销售人员";
    },
    //员工选择
    employeListSelectCheck (select) {
      this.fromdata.receptionName = select[0].userName;
      this.fromdata.receptionId = select[0].id;
      this.dialogVisible = false;
    },
    submitOrder () {
      this.$refs.fromdata.validate((valid) => {
        if (valid) {
          const { PartsList, BoutiqueList } = this.$refs;
          this.fromdata = {
            ...this.fromdata,
            receiptsTime: this.fromdata.receiptsTime
              ? parseTimeToYMDHMS(this.fromdata.receiptsTime)
              : "",
            memberGrade: this.fromdata.client.memberLevelDictValue,
            orderSellPartsList: PartsList.partsList,
            jpList: BoutiqueList.jpList,
          };
          this.saveData();
        } else {
          return false;
        }
      });
    },
    async saveData () {
      sessionStorage.removeItem("pendingWorkOrder");
      const { success } = this.fromdata.id
        ? await editSell(this.fromdata)
        : await addSell(this.fromdata);
      if (success) {
        this.$message({
          message: "操作成功",
          type: "success",
        });
        this.closeRouter();
      } else {
        this.$message.error("操作失败");
      }
    },
  },
  filters: {
    money (val) {
      val = val.toString().replace(/\$|\,/g, "");
      if (isNaN(val)) {
        val = "0";
      }
      let sign = val == (val = Math.abs(val));
      val = Math.floor(val * 100 + 0.50000000001);
      let cents = val % 100;
      val = Math.floor(val / 100).toString();
      if (cents < 10) {
        cents = "0" + cents;
      }
      for (let i = 0; i < Math.floor((val.length - (1 + i)) / 3); i++) {
        val =
          val.substring(0, val.length - (4 * i + 3)) +
          "," +
          val.substring(val.length - (4 * i + 3));
      }
      return "¥" + (sign ? "" : "-") + val + "." + cents;
    },
  },
};
</script>
<style lang="scss" scoped>
.text_right {
  text-align: right;
}
.color_red {
  font-size: 26px;
  color: red;
}
.ft18 {
  font-size: 18px;
}
</style>
